using System;
using System.Linq;

namespace TicTacToe
{
    /// <summary>
    /// Creates backing arrays suitable for holding the game state.
    /// </summary>
    internal static class BoardArrayFactory
    {
        internal static Symbol?[][] CreateBoardArray(int size)
        {
            var board = new Symbol?[size][];
            for (var i = 0; i < size; i++)
            {
                board[i] = new Symbol?[size];
            }
            return board;
        }

        /// <summary>
        /// Restores a game board from a speficied state.
        /// </summary>
        /// <param name="state">A string containing only the characters 'o', 'x', and ' '</param>
        /// <param name="boardSize">The size of a side of the square board. The length of the state string must be the board size squared.</param>
        /// <returns>An array representing a board populated with the supplied state.</returns>
        internal static Symbol?[][] CreateBoardArrayFromState(string state, int boardSize)
        {
            if (state.Length != (boardSize * boardSize))
                throw new ArgumentException(string.Format("The board state must contain exactly {0} symbols.", boardSize * boardSize), "state");

            var board = new Symbol?[boardSize][];

            //Add rows to the board one by one.
            for (var rowIndex = 0; rowIndex < boardSize; rowIndex++)
            {
                board[rowIndex] = state.Skip(rowIndex * boardSize).Take(boardSize).Select(SymbolHelpers.CharToSymbol).ToArray();
            }

            return board;
        }
    }
}